import CryptoJS from "crypto-js";
export const TOKEN_KEY: any = "PAYMENT_MANAGER_TOKEN";
const keyEnc = "B8UoO43VYyMSFZUw";
const keyIv = "PJeJViA1mumMDmJ1";

export const createUUID = (uid: Record<string, any>, obj: any = null) => {
  let user_id: any = uid;
  if (obj !== null || !obj) {
    for (const i in obj) {
      if (String(i).indexOf(String(uid)) > -1) {
        user_id = 1;
      }
    }
  }
  return user_id;
};
export const getEncString = (val: any) => {
  const keys = CryptoJS.enc.Utf8.parse(keyEnc);
  const iv = CryptoJS.enc.Utf8.parse(keyIv);
  const keyEncString = CryptoJS.enc.Utf8.parse(val);
  const keyEncrypted = CryptoJS.AES.encrypt(keyEncString, keys, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding,
  });
  return keyEncrypted.toString();
};
export const getDecString = (val: any) => {
  const keys = CryptoJS.enc.Utf8.parse(keyEnc);
  const iv = CryptoJS.enc.Utf8.parse(keyIv);
  const keyEncrypted = CryptoJS.AES.decrypt(val, keys, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding,
  });
  return keyEncrypted.toString(CryptoJS.enc.Utf8);
};

export const EncryptedSaveLocal = (key: any, value: any) => {
  const keyResult = getEncString(key);
  const valResult = getEncString(value);
  localStorage.setItem(keyResult, valResult);
};

export const DecryptedReadLocal = (key: any) => {
  const keyResult = getEncString(key);
  const result: any = localStorage.getItem(keyResult);
  if (result) {
    return getDecString(result);
  } else {
    return "";
  }
};

export const DecryptedDeleLocal = (key: any) => {
  const keyResult = getEncString(key);
  localStorage.removeItem(keyResult);
};

export const setToken = (token: any) => {
  const result = getToken();
  Object.assign(result, token);
  EncryptedSaveLocal(TOKEN_KEY, JSON.stringify(result));
};

export const getToken = () => {
  const token = DecryptedReadLocal(TOKEN_KEY);
  if (token) {
    return JSON.parse(token);
  } else {
    return {};
  }
};

export const delToken = () => {
  DecryptedDeleLocal(TOKEN_KEY);
};
